//
//  ZXXOAuthController.swift
//  M-Weibo
//
//  Created by ZXX on 16/4/18.
//  Copyright © 2016年 ZXX. All rights reserved.
//

import AFNetworking
import UIKit
import SVProgressHUD


// MARK: - webView 代理

extension ZXXOAuthController: UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 判断我们的urlString是否有值 二期前缀是否是我们回调页
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(REDIRECT_URI){
            // 拿到我们请求参数我们的request.URL?.absoluteString
            
            // 判断我们的request 的请求参数是否存在
            if let q = request.URL?.query{
                //code=30a3b19a1974d601ab48a606d7d42dcd
                // 获取code
                let code = q.substringFromIndex("code=".endIndex)
//                print("终于等到你还好没放弃:\(code)")
//                获取Access_token 的方法
                getUserAccount(code)
            }
        }
        
        return true
    }

    
}

class ZXXOAuthController: UIViewController {
    
    // MARK: -  设置View
    override func loadView() {
        view = webView
        
        webView.delegate = self
//        定义一个url
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        let request =  NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //设置UI
        setupUI()
    }
    // MARK: -  设置UI
    func setupUI(){
    view.backgroundColor = UIColor.whiteColor()
        setNav()
    }
    // MARK: -  Nav的一些设置
    func setNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
        navigationItem.title = "微博登录"
    }
    
    // MARK: - 监听方法
    @objc private func cancel(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func auto(){
//        print("自动填充了")
        
        let jsString = "document.getElementById('userId').value='\(CZWeiboName)';document.getElementById('passwd').value='\(CZWeiboPasswd)'"
        // JS注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)

    }
    
    // MARK: -  懒加载控件
    private lazy var webView: UIWebView = UIWebView()


}

// MARK: -  获取Access_token
extension ZXXOAuthController {
///    获取Access_token
    func getUserAccount(code: String){
    let urlString = "https://api.weibo.com/oauth2/access_token"
    let params = [
        "client_id":APPKEY,
        "client_secret":APPSECRET,
        "grant_type":"authorization_code",
        "code":code,
        "redirect_uri":REDIRECT_URI
    ]
        
        
                let manager = AFHTTPSessionManager()
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        manager.POST(urlString, parameters: params, progress: nil , success: { (_, response) -> Void in

//            转模型
            guard let dataDict = response as? [String: AnyObject] else{
                print("返回的不是一个字典数据")
                return
            }
            let account = ZXXUserAccount(dict: dataDict)
            
//            调用获取用户信息的方法把模型传递过去
            self.getUserInfo(account)
            }) { (_ , error ) -> Void in
                print("Access_token失败\(error)")
        }
        
    }
    ///获取用户信息
    func getUserInfo(account: ZXXUserAccount){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = [
            "access_token":account.access_token!,
            "uid":account.uid!
        ]
        let manager = AFHTTPSessionManager()
        manager.GET(urlString, parameters: params, progress: nil , success: { (_, response) -> Void in

            //            转模型
            guard let dataDict = response as? [String: AnyObject] else{
                print("返回的不是一个字典数据")
                return
            }
            // 对我们的account 的头像和昵称赋值
            account.avatar_large = dataDict["avatar_large"] as? String
            account.screen_name = dataDict["screen_name"] as? String
            
            //保存到沙盒
            ZXXUserAccountTools.sharedUserAccountTools.saveUserAccount(account)
            
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                // 发送通知告知appdelegate帮我们切换根视图
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchDefaultVcNSNotification, object: nil)
            })
            
            
            }) { (_ , error ) -> Void in
                print("失败\(error)")
        }
        
    }

        
    }
    

